import store from '@/store';
// 从本地获取 token
function getToken() {
  return uni.getStorageSync('token') || ''
}

export function request(url, method= 'GET', data = {}, options = {}, responseType= 'text') {
  const {
    showLoading = true
  } = options
  

  if (!url) {
    return Promise.reject(new Error('缺少请求 URL'))
  }

  if (showLoading) {
    uni.showLoading({ title: '加载中...', mask: true })
  }
  
  console.log(method,data,responseType,'---22')
  const BASEURL=import.meta.env.VITE_API_BASE_URL;
  console.log(BASEURL,'---21')
  let requestUrl=BASEURL+ '/' + url;
  if(options.oldApi){//老接口处理api
	  requestUrl=BASEURL.replace('/api', '')+url;
  }
  let isErr=data.isErr || false;
  delete data.isErr;
  console.log(data,`········【接口上送${url}】`)
  return new Promise((resolve, reject) => {
    uni.request({
      url: requestUrl,
      method: method.toUpperCase(),
      data,
	  responseType,
      header: {
		'token': getToken() || '',
        // 'Content-Type': 'application/json',
        // 'Authorization': getToken() ? `Bearer ${getToken()}` : '',
        // ...header
      },
      success: (res) => {
        const { statusCode, data } = res

        if (statusCode === 200) {
		  console.log(data,`········【接口返回${url}】`)
        if(url=='user/appLoginCaptchaImage' && data){
			  resolve(data)
		}else if(data?.data?.openid){
			  resolve(data)
		}else if (data.code === 200 || data.success) {
			resolve(data)
        }else if ([100,400].includes(data.code)) {
            uni.removeStorageSync('token')
            uni.showToast({ title: '登录失效，请重新登录', icon: 'none' })
            if(store.state.PROVIDER!=='weixin'){
				uni.reLaunch({ url: '/pagesB/login/login' })
			}
            reject(data)
        } else if(isErr){//不弹出错误
			  reject(data)
		} else {
            uni.showToast({ title: data.msg || '请求失败', icon: 'none' })
            reject(data)
          }
        } else {
          uni.showToast({ title: '网络异常', icon: 'none' })
          reject(res)
        }
      },
      fail: (err) => {
	    console.log(err,'---request-err')
        uni.showToast({ title: '请求出错', icon: 'none' })
        reject(err)
      },
      complete: (err) => {
        if (showLoading) {
          uni.hideLoading()
        }
      }
    })
  })
}
